﻿using DevState.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace DevState
{
    public class DevRegist
    {
        public bool Register(string str)
        {
            try
            {
                Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.Connect("172.16.1.159", 8002);
                string senddata = string.Format(@"{0}", str);
                clientSocket.Send(Encoding.Default.GetBytes(senddata));
                clientSocket.ReceiveTimeout = 3000;
                List<byte> data = new List<byte>();
                byte[] buffer = new byte[1024];
                int length = 0;
                while ((length = clientSocket.Receive(buffer)) > 0)
                {
                    for (int j = 0; j < length; j++)
                    {
                        data.Add(buffer[j]);
                    }
                    if (length < buffer.Length)
                    {
                        break;
                    }
                }
                data.RemoveRange(0, 57);

                if (data.Count > 0)
                {
                    string result = string.Empty;
                    result = Encoding.GetEncoding("utf-8").GetString(data.ToArray(), 0, data.Count);
                    Message message = JsonConvert.DeserializeObject<Message>(result);
                    if (message.Command == "COM_DEV_REGISTER" && message.Result == "0")
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                return false;
            }
            catch (Exception e)
            {
                return false;
            }
        }

    }

}
